package com.kanshu.ksgb.fastread.doudou.base.baseui;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.DownloadListener;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.NetUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.SwipeRefreshHelper;
import com.kanshu.ksgb.fastread.doudou.common.util.ToastUtil;
import com.kanshu.ksgb.fastread.doudou.common.util.DownloadUtils;
import com.kanshu.ksgb.fastread.doudou.common.view.EmptyLayout;
import com.kanshu.ksgb.fastread.doudou.common.view.MySwipeRefreshLayout;
import com.kanshu.ksgb.fastread.doudou.common.view.MyWebView;
import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import butterknife.ButterKnife;
import butterknife.BindView;

/**
 * Created by wcy on 2017\5\15 0015.
 */

public class BaseH5Fragment extends BaseFragment implements EmptyLayout.OnRetryListener, SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.progressBar)
    ProgressBar mProgressBar;
    @BindView(R.id.container)
    public FrameLayout mContainer;
    @BindView(R.id.empty_layout)
    protected EmptyLayout mEmptyLayout;
    @BindView(R.id.root_container)
    public LinearLayout mRootContainer;
    protected MyWebView mWebView;

    public static final String EXTRA_PARAM_URL = "url";
    public static final String EXTRA_PARAM_TITLE = "title";
    public static final String EXTRA_PARAM_EXTEND = "extend";
    public static final String EXTRA_IS_SHOW_LOADING = "is_show_loading";
    public static final String EXTRA_PARAM_NEEDINJECTJS = "needinjectjs";
    public static final String BRIDGE_NAME = "bridge";
    protected String mUrl;
    //扩展参数 用于加入头部参数
    protected Bundle mExtendParams;
    protected boolean isShowLoading;
    protected boolean mNeedInjectJs = true;
    @BindView(R.id.swipe_refresh)
    public MySwipeRefreshLayout mSwipeRefresh;
    @BindView(R.id.extra_container)
    public FrameLayout mExtraContainer;
    private DownloadUtils downloadUtils;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_h5_layout, null, false);
        ButterKnife.bind(this, view);
        parseArument();
        initView();
        if (!isLazyLoad()) {
            loadUrl();
            initWebSetting(mWebView, mWebView.getSettings());
        }
        return view;
    }

    protected void initView() {
        mWebView = new InnerWebView(getActivity());
        FrameLayout.LayoutParams p = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
        mContainer.addView(mWebView, p);
        mWebView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        mWebView.setHorizontalScrollBarEnabled(false);
        mWebView.setVerticalScrollBarEnabled(false);
        mEmptyLayout.setRetryListener(this);
        SwipeRefreshHelper.init(mSwipeRefresh, this);
        mSwipeRefresh.setEnabled(isEnableSwipeRefreshLayout());
        mWebView.setOnScrollChangedListener(new MyWebView.OnScrollChangedListener() {
            @Override
            public void onScrollChanged(int l, int t, int oldl, int oldt) {
                if (!isEnableSwipeRefreshLayout()) {
                    return;
                }
                if (t == 0) {
                    mSwipeRefresh.setEnabled(true);
                } else {
                    mSwipeRefresh.setEnabled(false);
                }
            }
        });
    }

    protected void parseArument() {
        Bundle arguments = getArguments();
        if (arguments == null) {
            return;
        }
        mUrl = arguments.getString(EXTRA_PARAM_URL);
        mExtendParams = arguments.getBundle(EXTRA_PARAM_EXTEND);
        isShowLoading = arguments.getBoolean(EXTRA_IS_SHOW_LOADING);
        mNeedInjectJs = arguments.getBoolean(EXTRA_PARAM_NEEDINJECTJS);
    }

    protected void loadUrl() {
        if (TextUtils.isEmpty(mUrl)) {
            return;
        }
        if (!NetUtils.isNetworkAvailable(getActivity())) {
            if (mProgressBar.getProgress() <= 0) {
                mEmptyLayout.setEmptyStatus(EmptyLayout.STATUS_NO_NET);
            } else {
                mEmptyLayout.hide();
            }
            mSwipeRefresh.setRefreshing(false);
            return;
        }
        if (mExtendParams != null) {
            Map<String, String> map = new HashMap<>();
            Set<String> set = mExtendParams.keySet();
            for (String s : set) {
                map.put(s, mExtendParams.get(s).toString());
            }
            mWebView.loadUrl(mUrl, map);
        } else {
            mWebView.loadUrl(mUrl);
        }
        JsBridge jsBridge = new JsBridge(getActivity());
        mWebView.addJavascriptInterface(jsBridge, BRIDGE_NAME);
        mSwipeRefresh.setRefreshing(false);
        mWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                if (!TextUtils.isEmpty(url) && (url.startsWith("http") || url.startsWith("https"))) {
                    if ( Build.VERSION.SDK_INT >= 23 && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0x33332);
                        return;
                    }
                    downloadUtils = DownloadUtils.getInstance(mContext);
                    downloadUtils.download(url, "第三方App", contentDisposition, "app.apk");
                    ToastUtil.showMessage("正在下载");
                    ((Activity) mContext).finish();
                }

            }
        });
    }

    protected void initWebSetting(WebView webview, WebSettings webSettings) {
        webSettings.setJavaScriptEnabled(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSettings.setBlockNetworkImage(false);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setTextZoom(100);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setSupportZoom(false);
        webSettings.setDisplayZoomControls(false);
        //webSettings.setSupportZoom(true);
        //webSettings.setBuiltInZoomControls(true);
        webSettings.setLoadWithOverviewMode(true);
        if (Build.VERSION.SDK_INT >= 21) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        if (NetUtils.isNetworkAvailable(getActivity())) {
            //webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        } else {
            webSettings.setCacheMode(WebSettings.LOAD_CACHE_ONLY);
        }
    }


    @Override
    protected void updateViews() {
        super.updateViews();
        loadUrl();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    protected boolean isLazyLoad() {
        return false;
    }

    @Override
    public void onRetry() {
        loadUrl();
    }

    @Override
    public void onRefresh() {
        loadUrl();
    }

    private class InnerWebView extends MyWebView {

        public InnerWebView(Context context) {
            super(context);
            WebSettings ws = getSettings();
            initWebSetting(this, ws);
            setWebChromeClient(new InnerWebChromeClient());
            setWebViewClient(new InnerWebViewClient());
        }

        public class InnerWebChromeClient extends WebChromeClient {

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                if (isAdded() && getActivity() != null && !getActivity().isFinishing()) {
                    final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                    builder.setTitle("提示")
                            .setMessage(message)
                            .setPositiveButton("确定", null);

                    // 不需要绑定按键事件
                    // 屏蔽keycode等于84之类的按键
                    builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
                        @Override
                        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                            return true;
                        }
                    });
                    // 禁止响应按back键的事件
                    builder.setCancelable(false);
                    AlertDialog dialog = builder.create();
                    if (getActivity() != null && !getActivity().isFinishing()) {
                        dialog.show();
                    }
                    result.confirm();// 因为没有绑定事件，需要强行confirm,否则页面会变黑显示不了内容。
                }
                return true;
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
                if (isAdded() && getActivity() != null && !getActivity().isFinishing()) {
                    final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                    builder.setTitle("提示")
                            .setMessage(message)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    result.confirm();
                                }
                            })
                            .setNeutralButton("取消", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    result.cancel();
                                }
                            });
                    builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            result.cancel();
                        }
                    });

                    // 屏蔽keycode等于84之类的按键，避免按键后导致对话框消息而页面无法再弹出对话框的问题
                    builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
                        @Override
                        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                            Log.v("onJsConfirm", "keyCode==" + keyCode + "event=" + event);
                            return true;
                        }
                    });
                    // 禁止响应按back键的事件
                    // builder.setCancelable(false);
                    AlertDialog dialog = builder.create();
                    if (getActivity() != null && !getActivity().isFinishing()) {
                        dialog.show();
                    }
                }


                return true;
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress); // 务必放在方法体的第一行执行；
                // to do your work
                if (mProgressBar != null && mProgressBar.getProgress() < newProgress) {
                    mProgressBar.setProgress(newProgress);
                    mProgressBar.setVisibility(VISIBLE);
                    if (newProgress >= 100) {
                        mProgressBar.setVisibility(GONE);
                        mEmptyLayout.hide();
                    }
                }
                // ...
            }

            @Override
            public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
                // to do your work
                // ...
                return super.onJsPrompt(view, url, message, defaultValue, result); // 务必放在方法体的最后一行执行，或者用if判断也行；
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if (TextUtils.isEmpty(title)) {
                    return;
                }
                // android 6.0 以下通过title获取
                if (title.contains("404") || title.contains("500") || title.contains("Error")) {
                    view.loadUrl("about:blank");// 避免出现默认的错误界面
                    if (mEmptyLayout != null) {
                        mEmptyLayout.setEmptyStatus(EmptyLayout.STATUS_NO_NET);
                    }
                }
            }
        }

        private class InnerWebViewClient extends WebViewClient {
            boolean isFirst;

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                DisplayUtils.visible(mProgressBar);
                if (!isShowLoading) {
                    if (mEmptyLayout != null) {
                        mEmptyLayout.setEmptyStatus(EmptyLayout.STATUS_HIDE);
                    }
                } else {
                    if (!isFirst) {
                        if (mEmptyLayout != null) {
                            mEmptyLayout.setEmptyStatus(EmptyLayout.STATUS_LOADING);
                        }
                        isFirst = true;
                    }
                }

            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // TODO:
                if (url.startsWith("weixin://wap/pay?") /*|| url.startsWith("https://mapi.alipay.com")*/) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    startActivity(intent);
                    return true;
                }
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                DisplayUtils.gone(mProgressBar);
                if (mEmptyLayout != null) {
                    mEmptyLayout.hide();
                }
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                DisplayUtils.gone(mProgressBar);
                if (mEmptyLayout != null) {
                    mEmptyLayout.setEmptyStatus(EmptyLayout.STATUS_NO_NET);
                }
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                super.onReceivedSslError(view, handler, error);
                if (handler != null) {
                    handler.cancel();
                }
            }
        }

    }

    protected boolean isEnableSwipeRefreshLayout() {
        return false;
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(getActivity());
        MobclickAgent.onPageStart(getClass().getSimpleName());
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(getActivity());
        MobclickAgent.onPageEnd(getClass().getSimpleName());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mWebView.removeAllViews();
        mWebView.destroy();
        mWebView = null;
    }

    public WebView getWebview() {
        return mWebView;
    }
}
